package com.joven.shelltest.controller;

import com.joven.shelltest.dto.DealMessageDto;
import com.joven.shelltest.dto.MessageDto;
import com.joven.shelltest.utils.redisdelay.DelayedQueueProcessor;
import com.joven.shelltest.utils.redisdelay.RedisDelayListWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Random;

/**
 * redis延时队列
 * @Author wzj
 * @Date 2023-07-26 10:21
 **/
@RestController
@RequestMapping("/delay")
@RequiredArgsConstructor
public class RedisDelayController {

    private static final String TEST_DELAY_QUEUE = "test";
    private static final String DEMO_DELAY_QUEUE = "demo";

    private final RedisDelayListWrapper redisDelayListWrapper;
    private final Random random = new Random();

    @GetMapping("/hello")
    public String testShell(String path) {
        return "redis delay <>" + path;
    }

//    @GetMapping("/publish")
//    public String publish(String msg, Long delayTime) {
//        if (delayTime == null) {
//            delayTime = 10_000L;
//        }
//        String queue = random.nextBoolean() ? TEST_DELAY_QUEUE : DEMO_DELAY_QUEUE;
//        msg = queue + "#" + msg + "#" + (System.currentTimeMillis() + delayTime);
//        redisDelayListWrapper.publish(queue, msg, delayTime);
//        System.out.println("延时: " + delayTime + "ms后消费: " + msg + " now:" + LocalDateTime.now());
//        return "success!";
//    }
//
//    @Consumer(topic = TEST_DELAY_QUEUE)
//    public void consumer(DelayMsg delayMsg) {
//        System.out.println("TEST消费延时消息: " + delayMsg + " at:" + LocalDateTime.now());
//    }
//    @Consumer(topic = DEMO_DELAY_QUEUE)
//    public void consumerDemo(DelayMsg delayMsg) {
//        System.out.println("DEMO消费延时消息: " + delayMsg + " at:" + LocalDateTime.now());
//    }

    private final DelayedQueueProcessor queueProcessor;

    @PostMapping("/message")
    public void addMessageToQueue(@RequestBody MessageDto messageDto) {
        if(Objects.isNull(messageDto.getDelay())){
            messageDto.setDelay(10000L);
        }
        DealMessageDto dealMessageDto = new DealMessageDto();
        dealMessageDto.setMessage(messageDto.getMessage());
        dealMessageDto.setStatus("Done");
        dealMessageDto.setDealMethod("Handle");

        queueProcessor.addToQueue(messageDto.getId(), dealMessageDto, messageDto.getDelay());
        String msg = messageDto.getId() + "#" +  messageDto.getMessage() + "#" + (System.currentTimeMillis() + messageDto.getDelay());
        System.out.println("推送延时消息: " + msg + " now:" + LocalDateTime.now());
    }
}
